//
//  CharDetailViewController.m
//  HXSDK
//
//  Created by dllo on 16/8/17.
//  Copyright © 2016年 zty. All rights reserved.
//

#import "CharDetailViewController.h"
#import <AudioUnit/AudioUnit.h>
#import "ChatTableViewCell.h"
@interface CharDetailViewController ()<UITextViewDelegate, UITableViewDelegate, UITableViewDataSource, IEMChatProgressDelegate, EMChatManagerDelegate, AVAudioRecorderDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate>
/**myview*/
@property (nonatomic, strong) UIView *myView;
/**创建会话tableView*/
@property (nonatomic, strong) UITableView *tableView;
/**会话数组*/
@property (nonatomic, strong) NSMutableArray *chatArray;

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, assign) BOOL result;

@property (nonatomic, strong) UIButton *sendButton;


@property (nonatomic, retain) AVAudioRecorder *audioRecorder;
@property (nonatomic, assign) NSTimeInterval time;
/**录音地址*/
@property (nonatomic, strong) NSString *urlStr;
/**<#注释#>*/
@property (nonatomic, assign) BOOL sucess;
/**<#注释#>*/
@property (nonatomic, strong) UIButton *btn2;

@end

@implementation CharDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.buddy.username;
    _sucess = YES;
    self.chatArray = [NSMutableArray array];
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    self.navigationController.navigationBar.translucent = NO;
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, 150)];
    [self.view addSubview:_myView];
    _myView.backgroundColor = [UIColor grayColor];
    [self handle];
    [self creat];
    [self creatButtomView];
    UIButton *button0 = [self.view viewWithTag:1008];
    [button0 addTarget:self action:@selector(action0) forControlEvents:UIControlEventTouchUpInside];
    UIButton *button1 = [self.view viewWithTag:1009];
    [button1 addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];
    UIButton *button2 = [self.view viewWithTag:1010];
    [button2 addTarget:self action:@selector(action2) forControlEvents:UIControlEventTouchUpInside];

 }


- (void) creat {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-45-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.contentOffset = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX);
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[ChatTableViewCell class] forCellReuseIdentifier:@"tabCell"];
    
    
    [self createBttomView];
    //注册键盘出现的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘消失的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    // 接收消息
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)createBttomView {

    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, HEIGHT-45-64, WIDTH, 45)];
    //    imageView.backgroundColor = [UIColor blackColor];
    _imageView.image = [UIImage imageNamed:@"toolbar_bottom_bar"];
    _imageView.userInteractionEnabled = YES;
    [self.view addSubview:_imageView];
    
    // 键盘  语音  切换
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:@"chat_bottom_voice_press"] forState:UIControlStateNormal];

    btn1.frame = CGRectMake(5, 5, 37, 40);
    
    
    UIButton *voice = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:@"chat_bottom_voice_nor"] forState:UIControlStateHighlighted];
    voice.frame = CGRectMake(5, 5, 37, 40);
    
    
    [btn1 addTarget:self action:@selector(btn1Aciton) forControlEvents:UIControlEventTouchUpInside];
    [_imageView addSubview:btn1];
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(47, 6, WIDTH - 47 - 95, 32)];
    _textView.layer.cornerRadius = 6;
    _textView.tag = 1001;
    _textView.textAlignment = NSTextAlignmentRight;
    _textView.backgroundColor = [UIColor whiteColor];
    _textView.delegate = self;
    [_imageView addSubview:_textView];
    
    // 加号
    _btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btn2 setImage:[UIImage imageNamed:@"chat_bottom_up_nor"] forState:UIControlStateNormal];
    [_btn2 setImage:[UIImage imageNamed:@"chat_bottom_up_press"] forState:UIControlStateHighlighted];
    _btn2.frame = CGRectMake(WIDTH-90, -2, 50, 50);
    
    [_btn2 addTarget:self action:@selector(addView) forControlEvents:UIControlEventTouchUpInside];
    [_imageView addSubview:_btn2];
    
    // 表情
    UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn3 setImage:[UIImage imageNamed:@"chat_bottom_smile_nor"] forState:UIControlStateNormal];
    [btn3 setImage:[UIImage imageNamed:@"chat_bottom_smile_press"] forState:UIControlStateHighlighted];
    btn3.frame = CGRectMake(WIDTH-50, -2, 50, 50);
    [btn3 addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
    [_imageView addSubview:btn3];
    
    //语音发送
    self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.sendButton addTarget:self action:@selector(sendbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sendButton addTarget:self action:@selector(downAction:) forControlEvents:UIControlEventTouchDown];
    [self.sendButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    [_imageView addSubview:_sendButton];
    
}
// 语音
-(void)btn1Aciton {
    
    if (_result) {
        _sendButton.hidden = NO;
        _textView.hidden = YES;
        _sendButton.frame = CGRectMake(47, 6, WIDTH - 47 - 95, 32);
        [_sendButton setTitle:@"长按发送" forState:UIControlStateNormal];
    }else{
        _sendButton.hidden = YES;
        _textView.hidden = NO;
        
    }
    _result = !_result;
    
}

// 笑脸发送
- (void)send {
    
    
}
- (void) downAction:(UIButton *)button {
    _audioRecorder =  [self audioRecorder];
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
        _time = [[NSDate date] timeIntervalSince1970];
   
      
    }


}
#pragma mark - 录音
/*取得录音文件保存路径*/
-(NSURL *)getSavePath{
    _urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSInteger num = arc4random() % 1000;
    _urlStr = [_urlStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.caf", (long)num]];
    NSURL *url=[NSURL fileURLWithPath:_urlStr];
    return url;
    
}
/**取得录音文件设置*/
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM=[NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    return dicM;
}
/**获得录音机对象 */
-(AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url=[self getSavePath];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate=self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}
/**录音完成，录音完成后播放录音*/
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    if (flag) {
        NSLog(@"录音成功!");
    }
    
}
#pragma mark - 录音结束
- (void) sendbuttonAction:(UIButton *)button {
    [self.audioRecorder stop];
     NSTimeInterval timer = [[NSDate date] timeIntervalSince1970];
    EMChatVoice *voice = [[EMChatVoice alloc] initWithFile:_urlStr displayName:@"Audio"];
    voice.duration = (NSInteger)(timer - _time);
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithChatObject:voice];
     //message
    EMMessage *message = [[EMMessage alloc] initWithReceiver:_buddy.username bodies:@[body]];
    message.messageType = eMessageTypeChat;
    //发送消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:self prepare:^(EMMessage *message, EMError *error) {
        NSLog(@"即将发送");
    } onQueue:nil completion:^(EMMessage *message, EMError *error) {
        NSLog(@"发送完成%@", message);
        [self.chatArray addObject:message];
        [_tableView reloadData];
    } onQueue:nil];
    
}

- (void) cancelAction:(UIButton *)button {
    [_audioRecorder stop];
     NSLog(@"停止语音");
}



-(void)handle{
    //获取本地聊天信息,获取当前对象的会话
    EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.buddy.username conversationType:eConversationTypeChat];
    //加载会话信息

    self.chatArray = (NSMutableArray *)[conversation loadAllMessages];

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        
        [_tableView setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];
        
        [_textView resignFirstResponder];
        NSString *str =  _textView.text;
        _textView.text = nil;
        if (str.length == 0) {
            return nil;
        }
            //5.内容对象
            EMChatText *text = [[EMChatText alloc] initWithText:str];
            //4.消息体
            /* 
             EMTextMessageBody; 文本消息体
             EMImageMessagebody 图片消息体
             EMVideoMessageBody 视频消息体
             EMVoiceMessageBody 声音消息体
             */
            EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:text];
            //3.接受者
            NSString *reciver = self.buddy.username;
            //2.EMMessage对象
            EMMessage *msg = [[EMMessage alloc] initWithReceiver:reciver bodies:@[textBody]];
        
            //1.发送消息
        
            [[EaseMob sharedInstance].chatManager asyncSendMessage:msg progress:self prepare:^(EMMessage *message, EMError *error) {
                NSLog(@"消息即将发送");
            } onQueue:nil completion:^(EMMessage *message, EMError *error) {
                
                NSLog(@"消息发送完成");
            } onQueue:nil];
        
        /******************************/
        [self handle];
        [self.tableView reloadData];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}


-(void)addView{
  
    if (_sucess) {
        [UIView animateWithDuration:0.1 animations:^{
            _myView.frame = CGRectMake(0, HEIGHT - 214, WIDTH, 150);
            _imageView.frame = CGRectMake(0, HEIGHT - 109 - 150, WIDTH, 45);
            
        }];
        [self.view bringSubviewToFront:_myView];
        [_btn2 setImage:[UIImage imageNamed:@"减号"] forState:UIControlStateNormal];
    }else{
        [_btn2 setImage:[UIImage imageNamed:@"chat_bottom_up_nor"] forState:UIControlStateNormal];
        [UIView animateWithDuration:0.1 animations:^{
            _myView.frame = CGRectMake(0, HEIGHT  - 64, WIDTH, 150);
            _imageView.frame = CGRectMake(0, HEIGHT - 109, WIDTH, 45);
            
        }];

        
    }
    _sucess = !_sucess;
    
}
-(void)creatButtomView{
    NSArray *array = @[@"发视频",@"发图片",@"发表心情"];
    for (NSInteger i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(30 + 120 * i, 10, 100, 100);
        button.layer.cornerRadius = 10;
        [self.myView addSubview:button];
        button.backgroundColor = [UIColor orangeColor];
        [button setTitle:array[i] forState:UIControlStateNormal];
        button.tag = 1008 + i;
    }
    

}
-(void)action0{
    NSLog(@"0");
    
}
-(void)action1{
     NSLog(@"1");
}
-(void)action2{
   
    
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tabCell"];
    cell.message = _chatArray[indexPath.row];
    
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tabCell"];
    cell.message = _chatArray[indexPath.row];
    
    return cell.rowHeight;

}
-(void)setProgress:(float)progress forMessage:(EMMessage *)message forMessageBody:(id<IEMMessageBody>)messageBody{

}
//接受信息
-(void)didReceiveMessage:(EMMessage *)message{
    [_chatArray addObject:message];
    [self.tableView reloadData];
    
}

- (void)keyboardWasShown:(NSNotification*)aNotification {
    
    //键盘高度
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //    [_tableView setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];
    //表视图滚动至底部。
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = CGRectMake(0, -keyBoardFrame.size.height, WIDTH, HEIGHT-64-45);
        _imageView.frame = CGRectMake(0,  HEIGHT-45-64-keyBoardFrame.size.height, WIDTH, 45);
    }];
    
    

    
    
}

-(void)keyboardWillBeHidden:(NSNotification*)aNotification{
    _imageView.frame = CGRectMake(0, HEIGHT-45-64, WIDTH, 45);
    _tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-64-45);
    [_tableView reloadData];
    
}

@end
